<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>商品参数</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert title="注意：只允许为第三级分类设置相关参数"
            type="warning" show-icon> </el-alert>
            <!-- 商品分类 -->
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类：</span>
                    <el-cascader
                    v-model="selectedCateKeys"
                    :options="cateList"
                    :props="cateProps"
                    @change="handleChange"></el-cascader>
                </el-col>
            </el-row>
            <!-- tab页签区 -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button class="cat_opt" type="primary" size="mini" :disabled="isBtnDisabled"
                    @click="showAddManyParamsDialog">添加参数</el-button>
                    <el-table :data="manyTabData" border stripe>
                        <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag @close="closeTag(i,scope.row)" closable v-for="(item,i) in scope.row.attr_vals" :key="i">
                                    {{item}}
                                </el-tag>
                                
                                <el-input
                                    class="input-new-tag"
                                    placeholder="New Tag"
                                    v-model="scope.row.inputValue"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                    >
                                    </el-input>
                               
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column>
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteParams(scope.row.attr_id)" >删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button class="cat_opt"  type="primary" size="mini" :disabled="isBtnDisabled"
                    @click="showAddManyParamsDialog">添加参数</el-button>
                     <el-table :data="onlyTabData" border stripe>
                         <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag @close="closeTag(i,scope.row)" closable v-for="(item,i) in scope.row.attr_vals" :key="i">
                                    {{item}}
                                </el-tag>
                                
                                <el-input
                                    class="input-new-tag"
                                    v-model="scope.row.inputValue"
                                    placeholder="New Tag"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                    >
                                    </el-input>
                               </template>
                        </el-table-column>
                        <el-table-column type="index">#</el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column>
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteParams(scope.row.attr_id)" >删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!-- 添加动态参数对话框 -->
        <el-dialog
            title="添加参数"
            :visible.sync="addManyParamsDialogVisiable"
            width="30%"
            @close="addDialogClosed()"
            >
            <el-form :model="addParamsForm" :rules="paramsRules" ref="addParamsRef" label-width="100px" class="demo-ruleForm">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addParamsForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addManyParamsDialogVisiable = false">取 消</el-button>
                <el-button type="primary" @click="addParams">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改动态参数对话框 -->
        <el-dialog
            title="修改参数"
            :visible.sync="editManyParamsDialogVisiable"
            width="30%"
            @close="editDialogClosed()"
            >
            <el-form :model="editParamsForm" :rules="paramsRules" ref="editParamsRef" label-width="100px" class="demo-ruleForm">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editParamsForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editManyParamsDialogVisiable = false">取 消</el-button>
                <el-button type="primary" @click="editParams">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return{
            cateList:[],
            cateProps:{
                expandTrigger:'hover',
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            
            // 级联选择框双向绑定数据
            selectedCateKeys:[],
            activeName:'many',
            manyTabData:[],
            onlyTabData:[],
            inputVisibleno:true,
            addManyParamsDialogVisiable:false,
            editManyParamsDialogVisiable:false,
            addParamsForm:{},
            editParamsForm:{},
            paramsRules:{
                attr_name:[
                    { required: true, message: '请输入分类名称', trigger: 'blur' },
                        {
                            min: 2,
                            max: 10,
                            message: '分类名称的长度在 2 到 10 个字符',
                            trigger: 'blur',
                        }
                    ]
            },
        }
    },
    created(){
        this.getCateList()
        this.$refs.saveTagInput
    },
    methods:{
       async getCateList(){
            const {data:res} = await this.$http.get('categories')
            if(res.meta.status !== 200) return this.$message.error('获取列表失败')
            this.cateList = res.data;
            // console.log(res);
       },
        //级联选择框变化触发    
        handleChange(){
           this.getParamsInfo()
       },
        //    tab页签点击事件
       handleTabClick(){
           this.getParamsInfo()
        //    console.log(this.activeName);

       },
       async getParamsInfo(){
           if(this.selectedCateKeys.length !== 3)
           {
               this.selectedCateKeys=[]
               this.manyTabData = []
               this.onlyTabData = []
               return
           }
        //    选中的三级分类
            // console.log(this.selectedCateKeys);
            // 根据当前所选的id和面板获取对应的参数
            const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}})
            if(res.meta.status !== 200) return this.$message.error('获取参数失败')
            if(this.activeName === 'many'){
                this.manyTabData = res.data
            }else{
                this.onlyTabData = res.data
            }
            res.data.forEach(item => {
                item.attr_vals = item.attr_vals ? 
                item.attr_vals.split(' '):[]
                // 文本框显示隐藏
                item.inputVisible = false
                // 输入的值
                item.inputValue=''
            });
            console.log(res.data);

       },
       showAddManyParamsDialog(){
           this.addManyParamsDialogVisiable = true
       },
        addParams(){
                this.$refs.addParamsRef.validate(async valid =>{
               if(!valid)return
               const {data:res} = await this.$http.post(`categories/${this.cateId}/attributes`,{
                   attr_name:this.addParamsForm.attr_name,
                   attr_sel:this.activeName,
               })
               if(res.meta.status !== 201) return this.$message.error('添加失败')
               this.$message.success('添加成功')
               this.getParamsInfo()
               this.addManyParamsDialogVisiable = false
                
           })
           
       },
       addDialogClosed(){
            this.$refs.addParamsRef.resetFields()
       },
       async showEditDialog(attr_id){
           this.editManyParamsDialogVisiable = true
            const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`)
            this.editParamsForm = res.data
        },
        editParams(){
            this.$refs.editParamsRef.validate(async valid => {
                if(!valid) return
                 const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,{
                     attr_name:this.editParamsForm.attr_name,
                     attr_sel:this.activeName,
                     attr_vals:this.editParamsForm.attr_vals,
                 })
                  if(res.meta.status !== 200) return this.$message.error('修改失败')
                  this.$message.success('修改成功')
                    this.getParamsInfo()
                    this.editManyParamsDialogVisiable = false
            })
        },
        editDialogClosed(){
            this.$refs.editParamsRef.resetFields()
        },
        async deleteParams(attr_id){
            const configResult = await this.$confirm(
                '此操作将永久删除该参数, 是否继续?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
            if(configResult !== 'confirm') return this.$message.info('您已取消操作')
            const {data:res} = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
            if(res.meta.status !== 200) return this.$message.error('删除失败')
            this.$message.success('删除成功')
            this.getParamsInfo()
        },
        // 删除对应的索引项
        closeTag(i,row){
            row.attr_vals.splice(i,1)
            this.saveAttrVals(row)
        },
        // 文本框失去焦点或enter键触发
         handleInputConfirm(row){
             console.log(row);
            if(row.inputValue.trim().length === 0){
                row.inputValue=''
                return
            }
            // 输入内容合法
            row.attr_vals.push(row.inputValue.trim())
            
            // 需要发起请求，保存这次操作
            this.saveAttrVals(row)
            row.inputValue = ''
            
        },
        async saveAttrVals(row){
            const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
                attr_sel:row.attr_sel,
                attr_vals: row.attr_vals.join(' ')
            })
            
             if(res.meta.status !== 200) return this.$message.error('操作失败')
             this.$message.success('操作成功')
        },
        
    },
    computed:{
        // 如果按钮被禁用则返回true否则返回false
        isBtnDisabled(){
            if(this.selectedCateKeys.length !== 3){
                return true
            }return false
        },
        // 当前选中的三级分类    
        cateId(){
            if(this.selectedCateKeys.length === 3){
                return this.selectedCateKeys[2]
            }return null
        },
        titleText(){
            if(this.activeName === 'many'){
                return '动态参数'
            }return '静态参数'
        },
        
    }
}
</script>
<style lang="less" scoped>
.cat_opt{
    margin:10px 0;
}
.el-tag{
    margin: 10px;
}
.input-new-tag{
    width: 120px;
}
</style>